package dao;

import entity.GoodEntity;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import utilities.HibernateUtil;

import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.List;

public final class GoodDAO {
    public static boolean publish(int publisherid, String title,String detail,String price ,String tag,String picture){
        Session s = null;
        try{
            s = HibernateUtil.getSession();
            s.beginTransaction();
            GoodEntity newGood = new GoodEntity();
            newGood.setPublisherid(publisherid);
            newGood.setTitle(title);
            newGood.setState("new");
            newGood.setPublishtime(new Timestamp(System.currentTimeMillis()));
            if(detail!=null) newGood.setDetail(detail);
            if(price!=null) newGood.setPrice(price);
            if(tag != null) newGood.setTag(tag);
            if(picture != null) newGood.setPicture(picture);

            s.save(newGood);
            s.getTransaction().commit();
        }catch (Exception e){
            e.printStackTrace();
            s.getTransaction().rollback();
            return false;
        }finally{
            HibernateUtil.safeCloseSession(s);
        }

        return true;
    }

    public static boolean buySellOrDelete(int id,int buyerid,String newState){
        Session s = null;
        try{
            s = HibernateUtil.getSession();
            s.beginTransaction();
            String hql = "update GoodEntity good set good.state = :stt where good.id =:gid";
            Query query = s.createQuery(hql);
            query.setParameter("stt",newState);
            query.setParameter("gid",id);
            query.executeUpdate();
            s.getTransaction().commit();
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }finally {
            HibernateUtil.safeCloseSession(s);
        }

        return true;
    }

    public static GoodEntity[] getGoods(String tag,Timestamp from,int startat,int endat){
        Session s = null;
        List resultList = null;
        try{
            s = HibernateUtil.getSession();
            //select g.id,g.publisherid,g.title,g.detail,g.price,g.picture
            String hql;
            if(tag != null)
                hql = " from GoodEntity g where g.publishtime <=:tfrom and g.tag = :ttag and g.state in ('new','bought') order by g.publishtime desc";
            else
                hql = " from GoodEntity g where g.publishtime <=:tfrom and g.state in ('new','bought') order by g.publishtime desc";
            Query query = s.createQuery(hql);
            query.setParameter("tfrom",from);
            if(tag != null) query.setParameter("ttag",URLDecoder.decode(tag,"UTF-8"));
            //if(tag != null) System.out.println(URLDecoder.decode(tag,"UTF-8"));
            query.setFirstResult(startat);
            query.setMaxResults(endat - startat);
            resultList = query.list();
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }finally {
            HibernateUtil.safeCloseSession(s);
        }

        if(resultList == null)
            return null;
        else{
            GoodEntity[] entityArray = new GoodEntity[resultList.size()];
            for(int i=0;i<resultList.size();i++)
                entityArray[i] = (GoodEntity) resultList.get(i);
            return entityArray;
        }

    }

    public static GoodEntity[] searchGoods(String keyword,Timestamp from,int startat,int endat){
        Session s = null;
        List resultList = null;
        try{
            s = HibernateUtil.getSession();
            //select g.id,g.publisherid,g.title,g.detail,g.price,g.picture
            String hql = " from GoodEntity g where g.publishtime <=:tfrom and g.title like :tkey order by g.publishtime desc";
            Query query = s.createQuery(hql);
            query.setParameter("tfrom",from);
            query.setParameter("tkey","%"+ URLDecoder.decode(keyword,"UTF-8")+"%");
            //System.out.println("keyis "+URLDecoder.decode(keyword,"UTF-8"));
            query.setFirstResult(startat);
            query.setMaxResults(endat - startat);
            resultList = query.list();
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }finally {
            HibernateUtil.safeCloseSession(s);
        }

        if(resultList == null)
            return null;
        else{
            GoodEntity[] entityArray = new GoodEntity[resultList.size()];
            for(int i=0;i<resultList.size();i++)
                entityArray[i] = (GoodEntity) resultList.get(i);
            return entityArray;
        }
    }

    public static GoodEntity getGoodInfo(int id){
        Session s = null;
        GoodEntity entity = null;
        try{
            s = HibernateUtil.getSession();
            String hql = "from GoodEntity g where g.id = :iid";
            Query query = s.createQuery(hql);
            query.setParameter("iid",id);
            List result = query.list();
            entity = (GoodEntity)(result.get(0));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            HibernateUtil.safeCloseSession(s);
            return entity;
        }
    }
}
